package br.ufc.great.dtx.server.config;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.Vector;

/**
 * 
 * @author Leonardo Oliveira Moreira
 *
 * Classe utilizada para configurar a aplicação baseada no arquivo de configuração
 */
public final class Config {
	
	public static int DTX_SERVER_PORT = Integer.parseInt(getConfigValue("dtx.server.port"));
	public static String DTX_SERVER_HOST = getDTXServerHost();
	public static long DTX_SERVER_DEADLOCK_TIME = Long.parseLong(getConfigValue("dtx.server.deadlock.time"));
	
	public static final String DATABASE_URL = getConfigValue("database.url");
	public static final String DATABASE_USER = getConfigValue("database.user");
	public static final String DATABASE_PASSWORD = getConfigValue("database.password");
	public static final String DATABASE_NAME = getConfigValue("database.name");
	public static final String DATABASE_DOCUMENT = getConfigValue("database.document");
	
	public static final int GRANULARITY = Integer.parseInt(getConfigValue("dtx.granularity"));

	private Config() {

	}
	
	public static final Vector<DTXSite> getDTXAllSites() {
		String allSites = getConfigValue("dtx.allsites");
		Vector<DTXSite> sites = new Vector<DTXSite>();
		if (allSites != null && allSites.trim().length() > 0) {
			if (allSites.indexOf(";") == -1) {
				DTXSite site = new DTXSite(allSites.split(":")[0], Integer.parseInt(allSites.split(":")[1]));
				sites.add(site);
			}
			else {
				String[] sitesArray = allSites.split(";");
				for (int i = 0; i < sitesArray.length; i++) {
					DTXSite site = new DTXSite(sitesArray[i].split(":")[0], Integer.parseInt(sitesArray[i].split(":")[1]));
					sites.add(site);
				}
			}
		}
		return sites;
	}
	
	private static final String getDTXServerHost() {
		String host = "localhost";
		try {
			return InetAddress.getLocalHost().getHostAddress();
		}
		catch (UnknownHostException e) {
			
		}
		return host;
	}
	
	/**
	 * Método utilizado para retornar um valor chave do arquivo de configuração
	 * 
	 * @param key
	 * @return
	 */
	private static final String getConfigValue(String key) {
		String value = "";
		Properties properties = new Properties();
		try {
			String appPath = System.getProperty("user.dir");
			if (appPath.endsWith("bin"))
				appPath = appPath.substring(0, appPath.length() - "bin".length());
			properties.load(new FileInputStream(appPath + System.getProperty( "file.separator") + "config.properties"));
			value = properties.getProperty(key);
			if (value == null || value.trim().length() <= 0)
				value = "";
		}
		catch (IOException e) {
			value = "";
		}
		return value;
	}
		
}
